package cn.jbit.netty.client;

import io.netty.buffer.ByteBuf;
import io.netty.buffer.Unpooled;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.SimpleChannelInboundHandler;
import io.netty.util.CharsetUtil;

/**
 * 源码学院只为培养优秀的bat程序员而生
 *
 * @author 学员张在成
 * @data 2020/8/9
 */
public class NettyClientHandler extends SimpleChannelInboundHandler<ByteBuf> {

    /**
     *
     * @param channelHandlerContext
     * @param byteBuf
     * @throws Exception
     *
     * 读到数据时触发的方法
     *
     */
    @Override
    protected void channelRead0(ChannelHandlerContext channelHandlerContext, ByteBuf byteBuf) throws Exception {
        System.out.println("accept msg:"+byteBuf.toString(CharsetUtil.UTF_8));
    }

    /**
     *
     * 异常处理
     * @param ctx
     * @param cause
     * @throws Exception
     */
    @Override
    public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception{
        cause.printStackTrace();
        ctx.close();
    }

    /**
     *
     * @param ctx
     * @throws Exception (链接成功后写入数据)
     *
     * 通道被激活触发的操作
     *
     */
    @Override
    public void channelActive(ChannelHandlerContext ctx) throws Exception {

        for (int i=0;i<1;i++){
            ByteBuf byteBuf= Unpooled.copiedBuffer("hello netty server"+i,CharsetUtil.UTF_8);
            ctx.writeAndFlush(byteBuf);
        }
    }
}
